//
//  CNM_ShakeAnimation.swift
//  CNMTools
//
//  Created by MrHong on 2024/3/18.
//  左右摇摆动画

import UIKit

public struct CNMShakeAnimation {
    ///  左右摇摆效果
    /// - Parameters:
    ///   - view: 需要摇摆的视图
    ///   - mobileShake: 摇摆时是否需要手机震动
    public static func shakeAnimation(target view: UIView, mobileShake: Bool = true) {
        // 创建左右摇摆的动画
        let shakeAnimation = CAKeyframeAnimation(keyPath: "transform.translation.x")
        shakeAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
        shakeAnimation.duration = 0.6
        shakeAnimation.values = [-20.0, 20.0, -20.0, 20.0, -10.0, 10.0, -5.0, 5.0, 0.0]
        shakeAnimation.isAdditive = true
        shakeAnimation.repeatCount = 1
        shakeAnimation.isRemovedOnCompletion = true
        // 添加
        view.layer.add(shakeAnimation, forKey: "shake")

        // 手机震动
        if mobileShake {
            cnm_mobileShakeAnimation()
        }
    }
}

// MARK: - Private
private extension CNMShakeAnimation {
    static func cnm_mobileShakeAnimation() {
        var impactFeedbackgenerator: UIImpactFeedbackGenerator

        if #available(iOS 13.0, *) {
            impactFeedbackgenerator = UIImpactFeedbackGenerator(style: .soft)
        } else {
            impactFeedbackgenerator = UIImpactFeedbackGenerator(style: .medium)
        }
        impactFeedbackgenerator.prepare()
        impactFeedbackgenerator.impactOccurred()
    }
}
